﻿using System.Net;
using System.Net.Mail;
using System.Text;
using Unijovem.UI.Models;

namespace Unijovem.UI.Helpers
{
    public class MailHelper
    {
        public static void SendTemplatedEmail(Email email)
        {
            var fromAddress = new MailAddress(email.From.Email, email.From.DisplayName);
            var mailMessage = new MailMessage
                                  {
                                      Priority = MailPriority.Normal,
                                      Subject = email.Subject,
                                      Body = GetEmailBody(email.TemplatePath),
                                      SubjectEncoding = Encoding.GetEncoding("ISO-8859-1"),
                                      BodyEncoding = Encoding.GetEncoding("ISO-8859-1"),
                                      From = fromAddress,
                                      IsBodyHtml = true
                                  };

            mailMessage.To.Add(new MailAddress(email.To.Email, email.To.NomeCompleto));


            if (mailMessage.Body == "") return;

            //var auth = new NetworkCredential(email.From.Email, email.From.Password);
            //var smtp = new SmtpClient {Port = 587, EnableSsl = true, Host = "smtp.gmail.com", Credentials = auth};
            var smtp = new SmtpClient { Port = 25, EnableSsl = false, Host = "relay-hosting.secureserver.net", UseDefaultCredentials = true };
            smtp.Send(mailMessage);
        }

        public static string GetEmailBody(string templatePath)
        {
            var objWebClient = new WebClient();
            byte[] aRequestedHtml = objWebClient.DownloadData(templatePath);
            var objUtf8 = new UTF8Encoding();
            string strRequestedHtml = objUtf8.GetString(aRequestedHtml);

            return strRequestedHtml;
        }

        #region Nested type: Email

        public class Email
        {
            public From From { get; set; }
            public PessoaModel To { get; set; }
            public string Subject { get; set; }
            public string TemplatePath { get; set; }
        }

        #endregion

        #region Nested type: From

        public class From
        {
            public string Email { get; set; }
            public string DisplayName { get; set; }
            public string Password { get; set; }
        }

        #endregion
    }
}